import React, { PureComponent, Fragment } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { connect } from 'dva'
import { uploadUrl } from '@/config/index'

import {
  Card,
  Tabs,
  message,
  Button,
  Table,
  Select,
  Modal,
  Form,
  Input,
  Icon,
  Upload,
  Popconfirm,
  Radio,
  Badge,
  Divider,
  Spin
} from 'antd'
import { LZFormItem } from '@/components/LZForm'
import commonApi from '@/services/common'
import { getToken } from '@/utils/localStorage'
import categoryService from './service'
import Goods from './goods'
import MyPageTable from '@/components/MyPageTable'
import { onTableData } from '@/utils/utils'

const { TabPane } = Tabs
const { Option } = Select
@connect(({ category }) => ({
  ...category
}))
@Form.create()
class Category extends PureComponent {
  state = {
    pageNumber: 1,
    pageSize: 10,
    total: 10,
    current: 1,

    iconFileList: [],
    icon: '',
    bannerIcon: '',
    bannerIconFileList: [],

    tabInfo: {},
    channerIds: [],
    tabActiveKey: '',
    newTabActiveKey: null,
    loading: true,
    addFirstVisible: false, //
    title: '',
    imgVisible: false,
    addGoods: false,
    goodsTitle: '',
    categoryId: '',
    secondCategory: undefined, // 名称的默认值
    secondCategorySort: undefined, // 排序的默认值
    secondId: undefined,
    firstConfirmLoading: false,
    // 同步类目
    sourceCategory: [],
    synchronizeChannel: [],
    secondary: [],
    category: [],
    channelData: [],
    zfbCode: '',
    parId: ''
  }

  columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
      key: 'id'
    },
    {
      title: '二级类目名称',
      dataIndex: 'name',
      align: 'center',
      key: 'name'
    },
    {
      title: '图片',
      dataIndex: 'icon',
      align: 'center',
      key: 'icon',
      render: text => <img src={text} className="table-cell-img" alt="" />
    },
    {
      title: '排序',
      dataIndex: 'sortRule',
      align: 'center',
      key: 'sortRule'
    },
    {
      title: '上线时间',
      dataIndex: 'createTime',
      align: 'center',
      key: 'createTime'
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      key: 'status',
      render: text => {
        const success = text === 1
        const status = success ? 'success' : 'default'
        const badgeText = success ? '有效' : '失效'
        return <Badge status={status} text={badgeText} />
      }
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (text, record) => {
        return (
          <div>
            <a onClick={() => this.addSeconds(record)}>添加三级类目</a>
            <Divider type="vertical" />
            <a onClick={() => this.editSecond(record)}>修改</a>
            <Divider type="vertical" />
            <a onClick={() => this.goodsList(record.id)}>查看三级类目</a>
            <Divider type="vertical" />
            <Popconfirm
              title="确定删除该类目吗？"
              onConfirm={() => this.deleteCategory(record.id)}
            >
              <a>删除</a>
            </Popconfirm>
          </div>
        )
      }
    }
  ]

  componentDidMount() {
    this.getCategory()
    this.getChannel()
  }

  // 获取一级类目
  getCategory = () => {
    categoryService.selectParentCategoryList().then(res => {
      // 获取一级类目成功后，默认展开一级类目的子目录，需要获取id，请求该类目的子目录
      if (res.length > 0) {
        const id = this.state.newTabActiveKey
          ? this.state.newTabActiveKey
          : res[0].id.toString()
        this.getSecondaryCategory(id)
        this.setState(
          {
            category: res,
            tabActiveKey: this.state.newTabActiveKey
              ? this.state.newTabActiveKey
              : id
          },
          () => {}
        )
      }
    })
  }

  // 获取上架渠道信息
  getChannel = () => {
    commonApi.selectPlateformChannel().then(res => {
      this.setState({
        channelData: res || []
      })
    })
  }

  // 获取二级类目
  getSecondaryCategory = (
    id = this.state.tabActiveKey,
    type = '',
    name = ''
  ) => {
    if (type === '同步') {
      this.props.dispatch({
        type: 'category/getSynchronizeSecondaryCategory',
        payload: {
          id,
          name
        },
        callback: res => {
          if (res.msg !== '操作成功') {
            message.error(`获取目标下的二级类目失败：${res.msg}`)
          }
        }
      })
    } else {
      categoryService
        .queryOpeCategoryPage({
          pageNumber: this.state.current,
          pageSize: this.state.pageSize,
          parentId: id
        })
        .then(res => {
          this.setState({
            loading: false,
            secondary: res.records,
            total: res.total,
            current: res.current
          })
        })
    }
  }

  // 页签的跳转
  onTabChange = key => {
    const { tabActiveKey } = this.state
    if (key !== tabActiveKey) {
      this.setState(
        {
          loading: true,
          tabActiveKey: key
        },
        () => {
          this.getSecondaryCategory(key)
        }
      )
    }
  }

  // 添加一级类目
  addFirst = () => {
    this.setState({
      addFirstVisible: true,
      title: '添加一级类目',
      icon: '',
      bannerIcon: '',
      iconFileList: [],
      bannerIconFileList: []
    })
  }

  // 添加二级类目
  addSecond = () => {
    this.setState({
      addFirstVisible: true,
      title: '添加二级类目',
      icon: '',
      bannerIcon: '',
      tabInfo: {}
    })
  }
  // 添加三级类目
  addSeconds = e => {
    this.setState({
      addFirstVisible: true,
      title: '添加三级类目',
      icon: '',
      bannerIcon: '',
      tabInfo: {},
      parId: e.id
    })
  }

  // 添加类目的确认
  handleOkFirst = () => {
    this.props.form.validateFields((err, value) => {
      if (!err) {
        this.setState({
          firstConfirmLoading: true
        })
        const { tabActiveKey, tabInfo, title, icon, bannerIcon } = this.state
        const newKey = tabActiveKey
        if (title === '一级类目编辑' || title === '二级类目编辑') {
          // 修改
          const payload = {
            id: tabInfo.id,
            ...value,
            icon,
            bannerIcon
            // type: this.state.title === '添加二级类目' ? 2 : 1,//一级类目传1，二级传2
          }
          if (title === '二级类目编辑') {
            payload.bannerIcon = icon
          }
          categoryService.editFirstCategory(payload).then(res => {
            this.setState(
              {
                addFirstVisible: false,
                firstConfirmLoading: false,
                iconFileList: [],
                bannerIconFileList: []
              },
              () => {
                this.props.form.resetFields()
                this.getCategory()
              }
            )
          })
        } else {
          // 新增
          if (this.state.title === '添加三级类目') {
            categoryService
              .addFirstCategory({
                ...value,
                type: 3,
                parentId: this.state.parId,
                sortRule: 0
              })
              .then(res => {
                message.success('添加成功')
                this.setState(
                  {
                    addFirstVisible: false,
                    newTabActiveKey: newKey,
                    iconFileList: [],
                    bannerIconFileList: [],
                    firstConfirmLoading: false
                  },
                  () => {
                    this.props.form.resetFields()
                    this.getCategory()
                  }
                )
              })
              .catch(() => {
                this.setState({
                  firstConfirmLoading: false
                })
              })
          } else {
            categoryService
              .addFirstCategory({
                name: value.name,
                channerIds: value.channerIds,
                icon: icon,
                bannerIcon,
                parentId: title === '添加二级类目' ? this.state.parentId : 0,
                sortRule: value.sortRule,
                type: this.state.title === '添加二级类目' ? 2 : 1, // 一级类目传1，二级传2
                id:
                  this.state.title === '添加二级类目'
                    ? this.state.parentId
                    : null, // 一级就是1-渠道值，二级就是parentId
                zfbCode: value.zfbCode
              })
              .then(res => {
                message.success('添加成功')
                this.setState(
                  {
                    addFirstVisible: false,
                    newTabActiveKey: newKey,
                    iconFileList: [],
                    bannerIconFileList: [],
                    firstConfirmLoading: false
                  },
                  () => {
                    this.props.form.resetFields()
                    this.getCategory()
                  }
                )
              })
              .catch(() => {
                this.setState({
                  firstConfirmLoading: false
                })
              })
          }
        }
      }
    })
  }

  // 上传的回调
  handleUploadChange = ({ file, fileList, event }, type) => {
    const filelist = [...fileList] || []
    if (file.status === 'done') {
      if (type === 'icon') {
        this.setState({
          icon: file.response.data
        })
      } else {
        filelist.map(item => {
          this.setState({
            bannerIcon: item.response.data
          })
        })
      }
    }
    if (type === 'icon') {
      this.setState({
        iconFileList: fileList
      })
    } else {
      this.setState({
        bannerIconFileList: fileList
      })
    }
  }

  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true
    })
  }

  // 上传后删除的回调
  onRemove = type => {
    if (type === 'icon') {
      this.setState({
        icon: '',
        iconFileList: []
      })
    } else {
      this.setState({
        bannerIconFileList: [],
        bannerIcon: ''
      })
    }
  }

  // 删除类目
  deleteCategory = (id = '') => {
    categoryService
      .deleteCategory({
        id: id || this.state.tabActiveKey
      })
      .then(res => {
        message.success('删除成功')
        this.getCategory()
      })
  }

  // 编辑一级类目
  editFirst = () => {
    const { category, tabActiveKey } = this.state
    const tabInfo = category.find(f => f.id === Number(tabActiveKey)) || {}
    const iconFileList = [{ uid: 1, url: tabInfo.icon }]
    const bannerIconFileList = [{ uid: 1, url: tabInfo.bannerIcon }]
    console.log(tabInfo)
    this.setState({
      addFirstVisible: true,
      title: '一级类目编辑',
      channerIds: tabInfo.channerIds,
      icon: tabInfo.icon,
      bannerIcon: tabInfo.bannerIcon,
      tabInfo,
      iconFileList,
      bannerIconFileList
    })
  }

  // 二级类目编辑
  editSecond = data => {
    const iconFileList = [{ uid: 1, url: data.icon }]
    this.setState({
      iconFileList,
      addFirstVisible: true,
      title: '二级类目编辑',
      channerIds: data.channerIds,
      icon: data.icon,
      bannerIcon: data.bannerIcon,
      secondCategory: data.name, // 名称的默认值
      secondCategorySort: data.sortRule, // 排序的默认值
      secondId: data.id,
      tabInfo: data,
      zfbCode: data.zfbCode
    })
  }

  // 添加前台类目商品
  addCategoryGoods = () => {
    this.setState({
      addGoods: true,
      goodsTitle: '添加类目商品'
    })
  }

  goodsCancel = () => {
    this.setState({ addGoods: false })
  }

  // 商品列表
  goodsList = id => {
    this.setState({
      addGoods: true,
      goodsTitle: '查看商品列表',
      categoryId: id
    })
  }

  renderUpload = type => {
    if (type === 'icon') {
      return (
        <div>
          <Icon type="plus" />
        </div>
      )
    }
    return (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">图片上传</div>
      </div>
    )
  }

  renderChannel = (getFieldDecorator, isAddFirst) => {
    const isAddSeconds = this.state.title === '添加三级类目'
    const { channelData, channerIds } = this.state
    return (
      <LZFormItem
        field="channerIds"
        label="上架渠道"
        getFieldDecorator={getFieldDecorator}
        lzIf={isAddFirst}
        requiredMessage="上架渠道不能为空"
        initialValue={channerIds}
      >
        <Select placeholder="请选择上架渠道" mode="multiple">
          {channelData &&
            channelData.map(item => (
              <Option key={item.appId} value={item.channelId}>
                {' '}
                {item.channelName}{' '}
              </Option>
            ))}
        </Select>
      </LZFormItem>
    )
  }

  //table 页数
  onPage = e => {
    this.setState(
      {
        current: e.current
      },
      () => {
        this.getSecondaryCategory()
      }
    )
  }

  render() {
    const {
      category,
      secondary,
      tabActiveKey,
      loading,
      addFirstVisible,
      title,
      imgVisible,
      addGoods,
      goodsTitle,
      categoryId,
      secondCategorySort,
      secondCategory,
      firstConfirmLoading,
      tabInfo,
      iconFileList,
      bannerIconFileList,
      bannerIcon,
      icon
    } = this.state
    const { name, sortRule, jumpUrl, status, parentId, zfbCode } = tabInfo
    const { getFieldDecorator } = this.props.form
    const isAddFirst = title === '添加一级类目'
    const isEditFirst = title === '一级类目编辑'
    const isEditSecond = title === '二级类目编辑'
    const isAddSecond = title === '添加二级类目'
    const isAddSeconds = title === '添加三级类目'

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    const imgUploadValidate = {
      validator: (rule, value, callback) => {
        if (!value && bannerIcon) {
          callback('图片不能为空')
        }
        callback()
      }
    }

    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: this.state.total,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      )
    }

    return (
      <PageHeaderWrapper
        title={false}
        className="nav-tab"
        content={
          <div>
            <Button type="primary" onClick={this.addFirst}>
              添加一级类目
            </Button>
            <Button onClick={this.editFirst}>修改一级类目</Button>
            <Popconfirm
              onConfirm={() => this.deleteCategory(0)}
              title={`确定要删除类目吗？`}
            >
              <Button style={{ margin: '10px' }}>删除一级类目</Button>
            </Popconfirm>
            {/* <Button type='primary' onClick={this.addCategoryGoods}>添加前台类目商品</Button> */}
            <Tabs
              activeKey={tabActiveKey}
              onChange={this.onTabChange}
              animated={false}
            >
              {category &&
                category.map(item => (
                  <TabPane tab={item.name} key={String(item.id)} />
                ))}
            </Tabs>
          </div>
        }
      >
        <Card bordered={false} style={{ marginTop: 20 }}>
          <Button onClick={this.addSecond} className="mb-18">
            添加二级类目
          </Button>
          <MyPageTable
            onPage={this.onPage}
            paginationProps={paginationProps}
            dataSource={secondary}
            columns={this.columns}
          />
        </Card>
        <Modal
          title={title}
          visible={addFirstVisible}
          onOk={this.handleOkFirst}
          confirmLoading={firstConfirmLoading}
          onCancel={() => {
            this.props.form.resetFields()
            this.setState({
              addFirstVisible: false,
              channerIds: [],
              fileList: [],
              bannerIcon: '',
              tabInfo: {},
              parId: ''
            })
          }}
        >
          <Form {...formItemLayout}>
            {this.renderChannel(getFieldDecorator, isAddFirst || isEditFirst)}
            <LZFormItem
              field="first"
              label="所属一级类目"
              getFieldDecorator={getFieldDecorator}
              lzIf={isAddSecond || isAddSeconds}
              // lzIf={isAddSecond || !isAddSeconds}
              requiredMessage="所属一级类目不能为空"
              initialValue={parentId}
            >
              <Select
                placeholder="请选择所属一级类目"
                onChange={value => this.setState({ parentId: value })}
              >
                {category &&
                  category.map(item => (
                    <Option value={item.id} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
              </Select>
            </LZFormItem>

            <LZFormItem
              field="name"
              label="二级类目名称"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="类目名称不能为空"
              lzIf={isEditSecond}
              initialValue={name}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            <LZFormItem
              field="name"
              label="类目名称"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="类目名称不能为空"
              lzIf={!isEditSecond}
              initialValue={name}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            {title !== '添加二级类目' && title !== '二级类目编辑' && (
              <LZFormItem
                field="zfbCode"
                label="支付宝类目"
                getFieldDecorator={getFieldDecorator}
                requiredMessage="类目排序不能为空"
                initialValue={zfbCode}
                lzIf={!isAddSeconds}
              >
                <Input placeholder="请输入" />
              </LZFormItem>
            )}

            <LZFormItem
              field="sortRule"
              label="类目排序"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="类目排序不能为空"
              initialValue={sortRule}
              lzIf={!isAddSeconds}
            >
              <Input placeholder="请输入" />
            </LZFormItem>

            <LZFormItem
              field="icon"
              label="icon图标"
              getFieldDecorator={getFieldDecorator}
              lzIf={isAddFirst || isEditFirst}
              required
              rules={[imgUploadValidate]}
              initialValue={icon}
            >
              <div className="upload-desc flex-column">
                <Upload
                  className="icon-upload"
                  accept="image/*"
                  action={uploadUrl}
                  headers={{
                    token: getToken()
                  }}
                  fileList={iconFileList}
                  listType="picture-card"
                  onPreview={this.handlePreview} // 预览
                  onRemove={() => this.onRemove('icon')} // 删除
                  onChange={evt => this.handleUploadChange(evt, 'icon')}
                >
                  {iconFileList.length >= 1 ? null : this.renderUpload('icon')}
                </Upload>
                <div className="size-desc">尺寸建议：43pt*43pt</div>
              </div>
            </LZFormItem>
            <LZFormItem
              field="bannerIcon"
              label="宣传图片"
              getFieldDecorator={getFieldDecorator}
              lzIf={isEditFirst || isAddFirst}
              required
              rules={[imgUploadValidate]}
              initialValue={bannerIcon}
            >
              <div className="upload-desc">
                <Upload
                  accept="image/*"
                  action={uploadUrl}
                  headers={{
                    token: getToken()
                  }}
                  fileList={bannerIconFileList}
                  listType="picture-card"
                  onPreview={this.handlePreview} // 预览
                  onRemove={this.onRemove} // 删除
                  onChange={this.handleUploadChange}
                >
                  {bannerIconFileList.length >= 1 ? null : this.renderUpload()}
                </Upload>
                <div className="size-desc">尺寸建议： 702px*198px</div>
              </div>
            </LZFormItem>
            <LZFormItem
              field="bannerIcon"
              label="宣传图片"
              getFieldDecorator={getFieldDecorator}
              lzIf={isEditSecond || isAddSecond}
              required
              rules={[imgUploadValidate]}
              initialValue={icon}
            >
              <div className="upload-desc">
                <Upload
                  accept="image/*"
                  action={uploadUrl}
                  headers={{
                    token: getToken()
                  }}
                  fileList={iconFileList}
                  listType="picture-card"
                  onPreview={this.handlePreview} // 预览
                  onRemove={this.onRemove} // 删除
                  onChange={evt => this.handleUploadChange(evt, 'icon')}
                >
                  {iconFileList.length >= 1 ? null : this.renderUpload('icon')}
                </Upload>
                <div className="size-desc">尺寸建议： 702px*198px</div>
              </div>
            </LZFormItem>
            <LZFormItem
              field="jumpUrl"
              label="跳转链接"
              getFieldDecorator={getFieldDecorator}
              lzIf={isAddFirst}
              required={false}
              initialValue={jumpUrl}
            >
              <Input placeholder="请输入" />
            </LZFormItem>
            {this.renderChannel(
              getFieldDecorator,
              !isAddFirst && !isEditFirst && !isAddSeconds
            )}
            <LZFormItem
              label="状态"
              field="status"
              required
              lzIf={isEditSecond}
              getFieldDecorator={getFieldDecorator}
              initialValue={status}
            >
              <Radio.Group>
                <Radio value={1}>有效</Radio>
                <Radio value={0}>无效</Radio>
              </Radio.Group>
            </LZFormItem>
          </Form>
        </Modal>
        {/* 图片的预览 */}
        <Modal
          visible={imgVisible}
          footer={null}
          onCancel={() => this.setState({ imgVisible: false })}
          width={600}
        >
          <img
            src={bannerIcon || null}
            alt=""
            style={{ width: '100%', paddingTop: 15 }}
          />
        </Modal>
        {/* 添加前台类目商品 */}
        <Modal
          visible={addGoods}
          title={'查看三级类目'}
          footer={null}
          destroyOnClose
          onCancel={this.goodsCancel}
          width={1000}
        >
          <Goods
            onCancel={this.goodsCancel}
            categoryId={categoryId}
            score={goodsTitle}
          />
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default Category
